package com.steak.transaction.service;

import com.steak.transaction.datasource.DatasourceScope;
import com.steak.transaction.result.R;
import lombok.AllArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author 刘牌
 * @Title:
 * @date 2022/3/19:59
 */
@Service
@AllArgsConstructor
public class StockService {
    private final JdbcTemplate jdbcTemplate;

    @DatasourceScope(scope = "slave2")
    public R decreaseStock(Integer commodityId){
        String sql = "UPDATE stock SET stock_num = ( SELECT sto.stock_num FROM ( SELECT ( st.stock_num - 1 ) stock_num FROM stock st WHERE st.commodity_id = "+commodityId+" ) sto) WHERE commodity_id = "+commodityId+"";
        jdbcTemplate.update(sql);
        return R.builder().code(200).msg("success").build();
    }

    @DatasourceScope(scope = "stockDbg")
    public R get(){
        Map<String, Object> map = jdbcTemplate.queryForMap("select * from stock");
        return R.builder().code(200).msg("success").data(map).build();
    }

    public R defaultDatasource() {
        Map<String, Object> map = jdbcTemplate.queryForMap("select * from stock");
        return R.builder().code(200).msg("success").data(map).build();
    }
}
